#include <unordered_map>

template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
        }
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
        }
    }

private:
    std::unordered_map<T, T> m;
};

class Solution
{
public:
    bool equationsPossible(vector<string> &equations)
    {
        auto ufs = UnionFindSet<char>(string("abcdefghijklmnoprstuvwxyz"));
        for (auto &equation : equations)
        {
            if (equation[1] == '=')
            {
                ufs.join(equation[0], equation[3]);
            }
        }
        for (auto &equation : equations)
        {
            if (equation[1] == '!')
            {
                if (ufs.find(equation[0]) == ufs.find(equation[3]))
                {
                    return false;
                }
            }
        }
        return true;
    }
};